<?php
namespace Com\Pay;
//玖捌
class Pay98{

    private $config = array();

    public function __construct($mchData){
        $this->config = $mchData;
    }

    /*生成支付连接*/
    public function getUrl($order_info){
        $merchantCode = $this->config['mch_id'];
        $notifyUrl = S_URL . '/Api/NotifyCallback/Pay98Notify';
        $order_sn = $order_info['ordernumber'];
        $price = $order_info['paymoney'] * 100;
        $post_data = array(
            "service" => 'v1_scan_pay',
            'version' => '1.0',
            "mch_no"  =>  $merchantCode,
            'charset' => 'UTF-8',
            "out_trade_no"  =>  $order_sn,
            "order_subject"  =>  "ChangbaoPay",
            'req_time'  => date('YmdHis'),
            'order_time'  => date('YmdHis'),
            "total_fee"  =>  $price,
            'sign_type' => 'MD5',
            "notify_url"     => $notifyUrl,
            'client_ip' => $_SERVER['HTTP_HOST'],
            'nonce_str' => randNumber(),
            'acquirer_type'   => $order_info['acquirer_type']
        );
        $post_data['sign'] = $this->setSign($post_data);
        $Send_url = 'http://payment.shopping98.com/scan/pay/gateway';
        $res = json_decode(https_request($Send_url , $post_data),true);
        if($res['code_url'] != ''){
            return $res;
        }else{
            $ret = '';
        }
        return $ret;
    }

    private function setSign($data = array(),$isNotify){
        ksort($data);
        // 拼接签名字符串
        $str = "";
        foreach($data as $key1 => $val){
            if($isNotify && $key1 == 'sign' || $key1 == 'sign_type') continue; // sign不加入验签
            if($val != '') $str = $str . $key1 . '=' . $val . '&';
        }
        $signTmpStr = rtrim($str,'&'); // 待加密的字符串
//        $sign = $isNotify ? md5($signTmpStr . '&key=' .$this->config['mch_key']) : md5($signTmpStr . $this->config['mch_key']);
        $sign = md5($signTmpStr . $this->config['mch_key']);
        return $sign;
    }

    //回调方法，把返回数据处理成统一规定返回
    public function response(){
        $data = parseData();
        $Sign = $data['sign'];
        // 进行签名验证
        $MySign =  $this->setSign($data,true);
        if($MySign == $Sign){
            // 验签成功
            if($data['resp_code'] == '0000' || $data['trade_state'] == 'S'){
                return true;
            }else{
                return false;
            }
        }else{
            // 失败
            return false;
        }
    }

}
